package net.wofly.sale.stock.service.impl;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.Organization;
import net.wofly.right.domain.Role;
import net.wofly.right.domain.User;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.sale.commodity.domain.Brand;
import net.wofly.sale.commodity.domain.Commodity;
import net.wofly.sale.commodity.domain.CommodityTerminal;
import net.wofly.sale.commodity.domain.CommodityType;
import net.wofly.sale.commodity.service.IBrandService;
import net.wofly.sale.commodity.service.ICommodityChannelService;
import net.wofly.sale.commodity.service.ICommodityService;
import net.wofly.sale.commodity.service.ICommodityTmlService;
import net.wofly.sale.commodity.service.ICommodityTypeService;
import net.wofly.sale.report.domain.StockDTO;
import net.wofly.sale.stock.domain.InOutStockDetail;
import net.wofly.sale.stock.domain.InStock;
import net.wofly.sale.stock.domain.OutStock;
import net.wofly.sale.stock.domain.Stock;
import net.wofly.sale.stock.domain.StockWarning;
import net.wofly.sale.stock.domain.Warehouse;
import net.wofly.sale.stock.repository.StockRepository;
import net.wofly.sale.stock.service.IInStockService;
import net.wofly.sale.stock.service.IOutStockService;
import net.wofly.sale.stock.service.IStockService;
import net.wofly.sale.stock.service.IStockWarningService;
import net.wofly.sale.stock.service.IWarehouseService;
import net.wofly.sale.stock.util.InStockType;
import net.wofly.sale.stock.util.OutStockType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service("iStockService")
@Transactional
public class StockServiceImpl implements IStockService {

    public static final String ADD_SINGAL = "+";
    public static final String SUB_SINGAL = "-";

    @Autowired
    StockRepository stockRepository;

    @Autowired
    IInStockService iInStockService;

    @Autowired
    IOutStockService iOutStockService;

    @Autowired
    IWarehouseService iWarehouseService;

    @Autowired
    IUserService iUserService;

    @Autowired
    ICommodityChannelService iCommodityChannelService;

    @Autowired
    ICommodityTypeService iCommodityTypeService;

    @Autowired
    IStockWarningService iStockWarningService;

    @Autowired
    ICommodityService iCommodityService;
    
    @Autowired
    IBrandService iBrandService;
    
    @Autowired
    ICommodityTmlService iCommodityTmlService ;
    
    @Autowired
    IUserRoleService iUserRoleService;
    
    @Autowired
    IOrganizationService iOrganizationService;
    

    @Override
    public Stock save(Stock entity) {
        return stockRepository.save(entity);
    }

    @Override
    public void delete(Stock entity) {
        stockRepository.delete(entity);
    }

    @Override
    public void delete(String key) {
        stockRepository.delete(key);
    }

    @Override
    public Stock findOne(String key) {
        return stockRepository.findOne(key);
    }

    @Override
    public Page<Stock> findAll(Specification specification, Pageable pageable) {
        return stockRepository.findAll(specification, pageable);
    }


    @Override
    public List<Stock> save(List<Stock> entityList) {
        return (List<Stock>) stockRepository.save(entityList);
    }

    @Override
    public Stock findByWarehouseIDAndCommodityTerminalID(String warehouseID, String commodityTerminalID) {
        return stockRepository.findByWarehouseIDAndCommodityTerminalID(warehouseID, commodityTerminalID);
    }
    
    @Override
    public List<Stock> findByWarehouseIDAndNumGreaterThan(String warehouseID, Integer num) {
        return stockRepository.findByWarehouseIDAndNumGreaterThan(warehouseID, num);
    }
    
    @Override
    public ReturnBean<InStock> addInStock(InStock inStock) {

        inStock.setInStockID(Identities.uuid2());
        inStock.setModifyDate(System.currentTimeMillis());

        User user = iUserService.findOne(inStock.getInStocker());
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "入库人ID不正确，未查询到对应的员工");
        }
    
        List<Role> roles = iUserRoleService.findRolesByUserID(inStock.getInStocker());
        if (CollectionUtils.isEmpty(roles)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未查询到入库人对应的角色，不能入库");
        }
    
        String firstPosition = roles.get(0).getRoleID().substring(0, 1);
        String warehouseID = user.getWarehouseID();
        if ("2".equals(firstPosition) || InStockType.订货会订单.getValue().equals(inStock.getInStockType())) {
            warehouseID = inStock.getWarehouseID();
        }

        if (StringUtils.isEmpty(warehouseID)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "入库人ID不正确，未查询到对应的仓库");
        }
        inStock.setWarehouseID(warehouseID);

        List<InOutStockDetail> stockDetails = inStock.getInOutStockDetails();
        for (InOutStockDetail detail : stockDetails) {
        		CommodityTerminal commodityTerminal = iCommodityTmlService.findOne(detail.getCommodityTerminalID());
            if (commodityTerminal == null) {
                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "入库详情中终端商品ID不正确");
            }
            detail.setInOutStockDetailID(Identities.uuid2());
            detail.setOperationType(1);
            detail.setModifyDate(System.currentTimeMillis());
        }

        InStock inStockDb = iInStockService.save(inStock);

        //增加库存
        addOrSubStock(inStock.getWarehouseID(), stockDetails, ADD_SINGAL);
        return new ReturnBean<InStock>(ResultCode.SUCCESS, "入库成功", inStockDb);
    }

    @Override
    public ReturnBean<OutStock> addOutStock(OutStock outStock) {
        outStock.setOutStockID(Identities.uuid2());
        outStock.setModifyDate(System.currentTimeMillis());
    
        User user = iUserService.findOne(outStock.getOutStocker());
        if (user == null) {
            return new ReturnBean<OutStock>(ResultCode.ERROR_SERVICE, "出库人ID不正确，未查询到对应的用户");
        }
    
        /*if (StringUtils.isEmpty(outStock.getWarehouseID()) && !outStock.isCustomerOutStock()) {
            //非客户出库
            if (StringUtils.isEmpty(user.getWarehouseID())) {
                return new ReturnBean<OutStock>(ResultCode.ERROR_SERVICE, "出库人ID不正确，未查询到对应的仓库");
            }
            outStock.setWarehouseID(user.getWarehouseID());
        }*/
    
        Warehouse warehouse = iWarehouseService.findOne(outStock.getWarehouseID());
        if (warehouse == null) {
            return new ReturnBean<OutStock>(ResultCode.ERROR_SERVICE, "仓库ID不正确，为查询到对应的仓库信息");
        }
    
        List<InOutStockDetail> stockDetails = outStock.getInOutStockDetails();
        if (null == stockDetails || stockDetails.isEmpty()) {
            return new ReturnBean<>(ResultCode.SUCCESS, "出库成功", iOutStockService.save(outStock));
        }
    
        for (InOutStockDetail detail : stockDetails) {
            detail.setInOutStockDetailID(Identities.uuid2());
            detail.setOperationType(2);
            detail.setModifyDate(System.currentTimeMillis());
        }
    
        //减少库存
        ReturnBean returnBean = addOrSubStock(outStock.getWarehouseID(), stockDetails, SUB_SINGAL);
        if (returnBean.getCode().equals(ResultCode.ERROR_SERVICE)) {
            return returnBean;
        }
    
        //TODO 检查是否达到库存预警值
    
        return new ReturnBean<>(ResultCode.SUCCESS, "出库成功", iOutStockService.save(outStock));
    }

    private ReturnBean<String> addOrSubStock(String warehouseID, List<InOutStockDetail> stockDetails, String addOrSub) {
        for (InOutStockDetail detail : stockDetails) {
            Stock stock = findByWarehouseIDAndCommodityTerminalID(warehouseID, detail.getCommodityTerminalID());
            if (stock == null) {
                stock = new Stock();
                stock.setStockID(Identities.uuid2());
                stock.setNum(0);
                stock.setWarehouseID(warehouseID);
                stock.setCommodityTerminalID(detail.getCommodityTerminalID());
                if (ADD_SINGAL.equals(addOrSub)) {
                    stock.setNum(stock.getNum() + detail.getNum());
                } else {
                    stock.setNum(stock.getNum() - detail.getNum());
                    //return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到对应的库存商品，不能进行出库操作");
                }
            } else {
                if (ADD_SINGAL.equals(addOrSub)) {
                    stock.setNum(stock.getNum() + detail.getNum());
                } else {
                    stock.setNum(stock.getNum() - detail.getNum());
                }
            }
            stock.setModifyDate(System.currentTimeMillis());
            save(stock);
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "操作成功");
    }

    @Override
    public ReturnBean<String> checkStockWarning(
            String warehouseID, String commodityTypeID, String
            commodityChannelID) {
        return null;
    }

    @Override
    public ReturnBean<PageWrapper<InStock>> getMyInStock(String userID, Integer pageNum, Integer pageSize) {
        User user = iUserService.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户ID不正确，未查询到对应的用户信息。userID= " + userID);
        }
        if (user.getWarehouseFlag().equals(0)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户没有仓库。userID= " + userID);
        }
        if (StringUtils.isEmpty(user.getWarehouseID())) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户仓库ID设置为空。userID= " + userID);
        }

        return buildPageInStock(user.getWarehouseID() , pageNum, pageSize) ;
    }

    @Override
    public ReturnBean<PageWrapper<OutStock>> getMyOutStock(String userID, Integer pageNum, Integer pageSize) {
        User user = iUserService.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户ID不正确，未查询到对应的用户信息。userID= " + userID);
        }
        if (user.getWarehouseFlag().equals(0)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户没有仓库。userID= " + userID);
        }
        if (StringUtils.isEmpty(user.getWarehouseID())) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户仓库ID设置为空。userID= " + userID);
        }

        return buildPageOutStock(user.getWarehouseID() , pageNum, pageSize) ;
    }

    @Override
    public ReturnBean<PageWrapper<Stock>> getMyStock(String userID, Integer pageNum, Integer pageSize) {
        User user = iUserService.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户ID不正确，未查询到对应的用户信息。userID= " + userID);
        }
        if (user.getWarehouseFlag().equals(0)) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户没有仓库。userID= " + userID);
        }
        if (StringUtils.isEmpty(user.getWarehouseID())) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户仓库ID设置为空。userID= " + userID);
        }
        
        return buildPageStock(user.getWarehouseID() , pageNum, pageSize) ;
    }
    
    private ReturnBean<PageWrapper<Stock>> buildPageStock(String warehouseID , Integer pageNum, Integer pageSize){
    	 	Pageable pageable = new PageRequest(pageNum - 1, pageSize);
    	 	Page<Object[]> page = stockRepository.findByWarehouseID(warehouseID, pageable) ;
    	 	List<Object[]> stockList = page.getContent();
    	 	List<Stock> rtnAtockList = new ArrayList<>() ;
    	 	Stock tmpStock; 
    	 	CommodityTerminal tmpCommodityTerminal ;
    	 	Commodity commodity ;
    	 	CommodityType commodityType ;
    	 	Brand brand ;
    	 	
        for (Object[] obj : stockList) {
        		tmpStock = (Stock)obj[0] ;
        		tmpCommodityTerminal = (CommodityTerminal)obj[1] ;
        		tmpStock.setCommodityTerminal(tmpCommodityTerminal);
        		tmpStock.setCommodityName(tmpCommodityTerminal.getCommodityTerminalName());
        		tmpStock.setCommodityCode(tmpCommodityTerminal.getCommodityTerminalCode());
        		
        		if (null != tmpCommodityTerminal ) {
        			if (!StringUtils.isEmpty(tmpCommodityTerminal.getCommodityID())) {
        				commodity = iCommodityService.findOne(tmpCommodityTerminal.getCommodityID()) ;
        				tmpStock.setCommodity(commodity);
                		
                		if (null != commodity ) {
                			if (!StringUtils.isEmpty(commodity.getCommodityTypeID())) {
                				commodityType = iCommodityTypeService.findOne(commodity.getCommodityTypeID() ) ;
                    			tmpStock.setCommodityType(commodityType);
                			}
                   
                			if (!StringUtils.isEmpty(commodity.getBrandID())) {
                				brand = iBrandService.findOne(commodity.getBrandID()) ;
                				tmpStock.setBrand(brand);
                			}
                		}
        			}
        		}
        		
        		rtnAtockList.add(tmpStock) ;
        }
    	 	
        PageWrapper<Stock> pw = new PageWrapper<>( pageNum,  pageSize, page.getTotalElements(), page.getTotalPages(),rtnAtockList) ;
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取库存列表成功！" ,pw);
    }
    
    private ReturnBean<PageWrapper<InStock>> buildPageInStock(String warehouseID , Integer pageNum, Integer pageSize){
    		Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        filterConditions.add(new FilterCondition(warehouseID, "warehouseID", ConditionRelate.and.name(),
                Operation.eq.name(), 1));
        condition.setFilterCondition(filterConditions);
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), InStock.class).getResult();

        Sort sort = new Sort(Sort.Direction.DESC, "modifyDate");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page<InStock> page = iInStockService.findAll(condition.getSpecification(), pageable);

        List<InStock> inStockList = page.getContent();
        for (InStock inStock : inStockList) {
            User inStockerUser = iUserService.findOne(inStock.getInStocker());
            if (inStockerUser != null) {
                inStock.setInStockerName(inStockerUser.getName());
            }

            inStock.setInStockTypeStr(InStockType.getName(inStock.getInStockType()));
        }

        return new ReturnBean<>(ResultCode.SUCCESS, "获取成功", PageHelper.toPage(page));
    }
    
    private ReturnBean<PageWrapper<OutStock>> buildPageOutStock(String warehouseID , Integer pageNum, Integer pageSize){
    		Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        filterConditions.add(new FilterCondition(warehouseID, "warehouseID", ConditionRelate.and.name(),Operation.eq.name(), 1));
        condition.setFilterCondition(filterConditions);
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), OutStock.class).getResult();

        Sort sort = new Sort(Sort.Direction.DESC, "modifyDate");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page<OutStock> page = iOutStockService.findAll(condition.getSpecification(), pageable);

        List<OutStock> outStockList = page.getContent();
        for (OutStock outStock : outStockList) {
            User outStockerUser = iUserService.findOne(outStock.getOutStocker());
            if (outStockerUser != null) {
                outStock.setOutStockerName(outStockerUser.getName());
            }

            outStock.setOutStockTypeStr(OutStockType.getName(outStock.getOutStockType()));
        }

        return new ReturnBean<>(ResultCode.SUCCESS, "获取成功", PageHelper.toPage(page));
    }
    
    
    @Override
	public ReturnBean<PageWrapper<Stock>> getAllStock(String companyOrgID, String shopOrgID, String employeeID,Integer pageNum, Integer pageSize) {
		if (null != companyOrgID && !StringUtils.isEmpty(companyOrgID) && "-1".equals(companyOrgID)) {
			return this.getCompanyStock(companyOrgID, pageNum, pageSize) ;
		}
		
		if  (null != shopOrgID && !StringUtils.isEmpty(shopOrgID)) {
			return this.getOrgStock(shopOrgID, pageNum, pageSize) ;
		}
		
		if  (null != employeeID && !StringUtils.isEmpty(employeeID)) {
			return this.getMyStock(employeeID, pageNum, pageSize) ;
		}
    	
		return null;
	}

    @Override
    public ReturnBean<PageWrapper<StockWarning>> getStockWarningByPage(
            String warehouseID, String commodityTypeID,
            String commodityTerminalID, Integer pageNum,
            Integer pageSize) {
        ReturnBean<PageWrapper<StockWarning>> result = validatorStockWarningParams(warehouseID, commodityTypeID,
        		commodityTerminalID);
        if (result != null) {
            return result;
        }

        Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        filterConditions.add(new FilterCondition(warehouseID, "warehouseID", ConditionRelate.and.name(),
                Operation.eq.name(), 1));
        filterConditions.add(new FilterCondition(commodityTypeID, "commodityTypeID", ConditionRelate.and.name(),
                Operation.eq.name(), 2));
        filterConditions.add(new FilterCondition(commodityTerminalID, "commodityTerminalID", ConditionRelate.and.name(),
                Operation.eq.name(), 3));
        condition.setFilterCondition(filterConditions);
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), StockWarning.class).getResult();

        Pageable pageable = new PageRequest(pageNum - 1, pageSize);

        Page<StockWarning> pageResult = iStockWarningService.findAll(condition.getSpecification(), pageable);

        return new ReturnBean<>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(pageResult));
    }

    private ReturnBean validatorStockWarningParams(
            String warehouseID, String commodityTypeID, String
            commodityTerminalID) {
        Warehouse warehouse = iWarehouseService.findOne(warehouseID);
        if (warehouse == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "仓库ID不正确，未查询到对应的仓库");
        }
        CommodityType commodityType = iCommodityTypeService.findOne(commodityTypeID);
        if (commodityType == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                    "commodityTypeID不正确，未查询到对应的商品分类");
        }
        CommodityTerminal commodityPkg = iCommodityTmlService.findOne(commodityTerminalID);
        if (commodityPkg == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                    "commodityPkgID不正确，未查询到对应的终端商品");
        }
        return null;
    }

    @Override
    public ReturnBean<StockWarning> setStockWarning(
            String warehouseID, String commodityTypeID, String
            commodityTerminalID, Integer num) {
        ReturnBean<StockWarning> result = validatorStockWarningParams(warehouseID, commodityTypeID, commodityTerminalID);
        if (result != null) {
            return result;
        }

        StockWarning stockWarning = new StockWarning();
        stockWarning.setStockWarningID(Identities.uuid2());
        stockWarning.setWarehouseID(warehouseID);
        stockWarning.setCommodityTypeID(commodityTypeID);
        stockWarning.setCommodityTerminalID(commodityTerminalID);
        stockWarning.setWarningNum(num);
        stockWarning.setModifyDate(System.currentTimeMillis());

        return new ReturnBean<>(ResultCode.SUCCESS, "查询成功", iStockWarningService.save(stockWarning));
    }

    @Override
    public List<Stock> findByWarehouseID(String warehouseID) {
        return stockRepository.findByWarehouseID(warehouseID);
    }

	@Override
	public ReturnBean<PageWrapper<Stock>> getCompanyStock(String companyID, Integer pageNum, Integer pageSize) {
		List<Warehouse> companyWarehouses = iWarehouseService.findByWarehouseTypeAndStatus("1", 1) ;
		if(null == companyWarehouses || companyWarehouses.isEmpty()) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库不存在！");
		}
		Warehouse companyWarehouse = companyWarehouses.get(0) ;
		if (null == companyWarehouse) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库不存在！");
		}
		
		if (StringUtils.isEmpty(companyWarehouse.getWarehouseID())) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库设置不正确！");
		}
		
		return buildPageStock(companyWarehouse.getWarehouseID() , pageNum, pageSize) ;
	}

	@Override
	public ReturnBean<PageWrapper<Stock>> getOrgStock(String orgID, Integer pageNum, Integer pageSize) {
		Organization org = iOrganizationService.findOne(orgID) ;
		if (null == org) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构不存在！");
		}
		
		if (org.getWarehouseFlag().equals(0)) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构没有设置仓库！");
		}
		
		if (StringUtils.isEmpty(org.getWarehouseID())) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构仓库设置不正确！");
		}
		
		return buildPageStock(org.getWarehouseID() , pageNum, pageSize) ;
	}

	@Override
	public ReturnBean<PageWrapper<InStock>> getAllInStock(String companyOrgID, String shopOrgID, String employeeID, Integer pageNum, Integer pageSize) {
		if (null != companyOrgID && !StringUtils.isEmpty(companyOrgID) && "-1".equals(companyOrgID)) {
			return this.getCompanyInStock(companyOrgID, pageNum, pageSize) ;
		}
		
		if  (null != shopOrgID && !StringUtils.isEmpty(shopOrgID)) {
			return this.getOrgInStock(shopOrgID, pageNum, pageSize) ;
		}
		
		if  (null != employeeID && !StringUtils.isEmpty(employeeID)) {
			return this.getMyInStock(employeeID, pageNum, pageSize) ;
		}
    	
		return null;
	}

	@Override
	public ReturnBean<PageWrapper<OutStock>> getAllOutStock(String companyOrgID, String shopOrgID, String employeeID, Integer pageNum, Integer pageSize) {
		if (null != companyOrgID && !StringUtils.isEmpty(companyOrgID) && "-1".equals(companyOrgID)) {
			return this.getCompanyOutStock(companyOrgID, pageNum, pageSize) ;
		}
		
		if  (null != shopOrgID && !StringUtils.isEmpty(shopOrgID)) {
			return this.getOrgOutStock(shopOrgID, pageNum, pageSize) ;
		}
		
		if  (null != employeeID && !StringUtils.isEmpty(employeeID)) {
			return this.getMyOutStock(employeeID, pageNum, pageSize) ;
		}
    	
		return null;
	}

	@Override
	public ReturnBean<PageWrapper<OutStock>> getCompanyOutStock(String companyID, Integer pageNum, Integer pageSize) {
		List<Warehouse> companyWarehouses = iWarehouseService.findByWarehouseTypeAndStatus("1", 1) ;
		if(null == companyWarehouses || companyWarehouses.isEmpty()) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库不存在！");
		}
		Warehouse companyWarehouse = companyWarehouses.get(0) ;
		if (null == companyWarehouse) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库不存在！");
		}
		
		if (StringUtils.isEmpty(companyWarehouse.getWarehouseID())) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库设置不正确！");
		}
		
		return buildPageOutStock(companyWarehouse.getWarehouseID() , pageNum, pageSize) ;
	}

	@Override
	public ReturnBean<PageWrapper<OutStock>> getOrgOutStock(String orgID, Integer pageNum, Integer pageSize) {
		Organization org = iOrganizationService.findOne(orgID) ;
		if (null == org) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构不存在！");
		}
		
		if (org.getWarehouseFlag().equals(0)) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构没有设置仓库！");
		}
		
		if (StringUtils.isEmpty(org.getWarehouseID())) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构仓库设置不正确！");
		}
		
		return buildPageOutStock(org.getWarehouseID() , pageNum, pageSize) ;
	}

	@Override
	public ReturnBean<PageWrapper<InStock>> getCompanyInStock(String companyID, Integer pageNum, Integer pageSize) {
		List<Warehouse> companyWarehouses = iWarehouseService.findByWarehouseTypeAndStatus("1", 1) ;
		if(null == companyWarehouses || companyWarehouses.isEmpty()) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库不存在！");
		}
		Warehouse companyWarehouse = companyWarehouses.get(0) ;
		if (null == companyWarehouse) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库不存在！");
		}
		
		if (StringUtils.isEmpty(companyWarehouse.getWarehouseID())) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "公司总仓库设置不正确！");
		}
		
		return buildPageInStock(companyWarehouse.getWarehouseID() , pageNum, pageSize) ;
	}

	@Override
	public ReturnBean<PageWrapper<InStock>> getOrgInStock(String orgID, Integer pageNum, Integer pageSize) {
		Organization org = iOrganizationService.findOne(orgID) ;
		if (null == org) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构不存在！");
		}
		
		if (org.getWarehouseFlag().equals(0)) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构没有设置仓库！");
		}
		
		if (StringUtils.isEmpty(org.getWarehouseID())) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "组织机构仓库设置不正确！");
		}
		
		return buildPageInStock(org.getWarehouseID() , pageNum, pageSize) ;
	}

    @Override
    public List<StockDTO> findByCountDate(Long countDate, Long countEndTime) {
        return stockRepository.findByCountDate();
    }
}
